﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TcpPictureDemo
{
    public partial class Form1 : UIForm
    {
        private const string IpAddress = "192.168.3.10";
        private const int JsonPort = 9999;
        private const int ImagePort1 = 7880;
        private const int ImagePort2 = 7879;
        private const string RtmpUrl = "rtmp://112.53.205.216:21935/myapp/1";
        private const int FrameWidth = 407;
        private const int FrameHeight = 394;
        private const string StartFlag = "START_FLAG";
        private const string EndFlag = "END_FLAG";

        private Socket _jsonSocket;
        private Socket _imageSocket1;
        private Socket _imageSocket2;

        void AddLog(string msg)
        {
            this.uiRichTextBox1.Invoke((MethodInvoker)delegate {
                this.uiRichTextBox1.AppendText(msg + "\r\n");
            });
        }

        public Form1()
        {
            InitializeComponent();
            InitializeSockets();
        }

        private void InitializeSockets()
        {
            _jsonSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _jsonSocket.Connect(IpAddress, JsonPort);
            AddLog($"{JsonPort}连接成功");

            BeginReceive(_jsonSocket);
        }

        private void BeginReceive(Socket socket)
        {
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    byte[] buffer = new byte[1024];
                    int length = socket.Receive(buffer);
                    if (length > 0)
                    {
                        string response = Encoding.Default.GetString(buffer);
                        AddLog("收到消息：" + response);
                        List<string> jsonList = ExtractJsonList(response);
                        foreach (string json in jsonList)
                        {
                            ProcessJson(json);
                        }
                    }
                }
            });
            thread.Start();
        }

        private void ProcessJson(string json)
        {
            json = json.Replace("\\", "");
            List<JObject> jsonArray = JsonConvert.DeserializeObject<List<JObject>>(json);
            foreach (JObject jObject in jsonArray)
            {
                AddLog(jObject.ToString());
            }
        }

        private List<string> ExtractJsonList(string input)
        {
            List<string> jsonList = new List<string>();

            int startIndex = input.IndexOf("start\"");
            int endIndex = input.IndexOf("\"end", startIndex + 1);

            while (startIndex != -1 && endIndex != -1)
            {
                string json = input.Substring(startIndex + 6, endIndex - startIndex - 6);
                jsonList.Add(json);

                startIndex = input.IndexOf("\"start\"", endIndex + 1);
                endIndex = input.IndexOf("\"end", startIndex + 1);
            }

            return jsonList;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseSocket(_jsonSocket);
            CloseSocket(_imageSocket1);
            CloseSocket(_imageSocket2);
        }

        private void CloseSocket(Socket socket)
        {
            if (socket != null)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                socket.Dispose();
            }
        }

        private void UIButton1_Click(object sender, EventArgs e)
        {
            var configJson1 = GetConfigJson(ImagePort1, "192.168.0.1");
            var configJson2 = GetConfigJson(ImagePort2, "0");
            SendData(configJson1);
            BeginReceiveImages(1);
            //Thread.Sleep(3000);
            SendData(configJson2);
            BeginReceiveImages(2);
        }

        private Dictionary<string, string> GetConfigJson(int port, string cameraPath)
        {
            return new Dictionary<string, string>
            {
                {"video_catch", ConfigurationManager.AppSettings["video_catch"]},
                {"MODULE", ConfigurationManager.AppSettings["MODULE"]},
                {"x1", ConfigurationManager.AppSettings["x1"]},
                {"y1", ConfigurationManager.AppSettings["y1"]},
                {"x2", ConfigurationManager.AppSettings["x2"]},
                {"y2", ConfigurationManager.AppSettings["y2"]},
                {"rtmpurl", RtmpUrl},
                {"port", port.ToString()},
                {"state", "open"},
                {"camera_path", cameraPath},
                {"FRAME_WIDTH", FrameWidth.ToString()},
                {"FRAME_HEIGHT", FrameHeight.ToString()}
            };
        }

        private void SendData(Dictionary<string, string> configJson)
        {
            try
            {
                string json = "{" + string.Join(", ", configJson.Select(kv => $"\"{kv.Key}\": \"{kv.Value}\"")) + "}";
                AddLog("发送数据: " + json);
                byte[] data = Encoding.ASCII.GetBytes(json);
                _jsonSocket.Send(data);
            }
            catch (Exception ex)
            {
                AddLog("发送数据失败: " + ex.Message);
            }
        }

        private void BeginReceiveImages(int i)
        {
            if (i == 1)
            {

                _imageSocket1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _imageSocket1.Connect(IpAddress, ImagePort1);
                AddLog($"{ImagePort1}连接成功");
                StartImageReceivingThread(_imageSocket1, pictureBox);
            }
            else
            {
                _imageSocket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _imageSocket2.Connect(IpAddress, ImagePort2);
                AddLog($"{ImagePort2}连接成功");
                StartImageReceivingThread(_imageSocket2, pictureBox1);
            }

        }

        private void StartImageReceivingThread(Socket socket, PictureBox pictureBox)
        {
            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    Image image = ReceiveImage(socket);
                    AddLog("读取到图像");
                    DisplayImage(image, pictureBox);
                }
            });
            thread.Start();
        }

        private Image ReceiveImage(Socket socket)
        {
            byte[] startFlagBytes = Encoding.UTF8.GetBytes(StartFlag);
            byte[] endFlagBytes = Encoding.UTF8.GetBytes(EndFlag);

            byte[] buffer = new byte[4096];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int bytesRead = socket.Receive(buffer, startFlagBytes.Length, SocketFlags.None);
                    if (bytesRead > 0)
                    {
                        string packet = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        if (packet.Equals(StartFlag))
                        {
                            AddLog("读取到START_FLAG");
                            break;
                        }
                    }
                }

                while (true)
                {
                    int bytesRead = socket.Receive(buffer);
                    if (bytesRead > 0)
                    {
                        ms.Write(buffer, 0, bytesRead);
                        if (ms.Length >= endFlagBytes.Length)
                        {
                            ms.Position = ms.Length - endFlagBytes.Length;
                            byte[] lastBytes = new byte[endFlagBytes.Length];
                            ms.Read(lastBytes, 0, endFlagBytes.Length);
                            if (Encoding.UTF8.GetString(lastBytes) == EndFlag)
                            {
                                AddLog("读取到END_FLAG");
                                ms.SetLength(ms.Length - endFlagBytes.Length);
                                break;
                            }
                        }
                    }
                }
                ms.Position = 0;
                return Image.FromStream(ms);
            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //clientSocket.Connect("192.168.3.5", 9999);

            //// 接收图像数据并显示在pictureBox中
            //Image image = ReceiveImage();
            //DisplayImage(image);
        }

        private void DisplayImage(Image image, PictureBox pictureBox)
        {
            if (pictureBox.InvokeRequired)
            {
                pictureBox.Invoke(new MethodInvoker(delegate () { pictureBox.Image = image; pictureBox.SizeMode = PictureBoxSizeMode.StretchImage; }));
            }
            else
            {
                pictureBox.Image = image;
                pictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
            }
        }
    }
}
